package cn.netctoss.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.stereotype.Repository;

import cn.netctoss.entity.Admin;
import cn.netctoss.entity.Cost;

/**
 * 持久层实现
 *
 */

@Repository("adminDAO")
public class AdminDAOJdbcImpl implements AdminDAO {

	@Resource(name = "ds")
	private DataSource ds;

	public Admin findByAdminCode(String adminCode) {

		Admin admin = null;
		Connection conn = null;
		try {
			conn = ds.getConnection();
			String sql = "select *from admin_info " + "where admin_code=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, adminCode);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				// 创建Admin对象
				admin = new Admin();
				admin.setAdminId(rs.getInt("admin_id"));
				admin.setAdminCode(adminCode);
				admin.setPassword(rs.getString("password"));
				admin.setName(rs.getString("name"));
				admin.setTelephone(rs.getString("telephone"));
				admin.setEmail(rs.getString("email"));
				admin.setEnrolldate(rs.getTimestamp("enrolldate"));
				return admin;
			}

		} catch (SQLException e) {
			// step1:记日志(保留日志)
			e.printStackTrace();
			/*
			 * step2:看异常能不能恢复. 如果不能够恢复(比如数据库服务暂停,网络中断,
			 * 这样的异常一般称之为系统异常),则提示用户稍后重试. 如果能够恢复:则立即恢复
			 */
			throw new RuntimeException("获取连接失败", e);

		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
		}
		return admin;
	}

	public List<Cost> findAll() {

		List<Cost> list = null;
		Connection conn = null;

		try {
			conn = ds.getConnection();
			String sql = "select *from cost " + "order by cost_id";
			Statement state = conn.createStatement();
			ResultSet rs = state.executeQuery(sql);
			list = new ArrayList<Cost>();
			while (rs.next()) {
				Cost c = new Cost();
				c.setCostId(rs.getInt("cost_id"));
				c.setName(rs.getString("name"));
				c.setBaseDuration(rs.getInt("base_duration"));
				c.setBaseCost(rs.getDouble("base_cost"));
				c.setUnitCost(rs.getDouble("unit_cost"));

				c.setStatus(rs.getString("status"));
				c.setDescr(rs.getString("descr"));
				c.setCreatime(rs.getTimestamp("creatime"));
				c.setStartime(rs.getTimestamp("startime"));
				c.setCostType(rs.getString("cost_type"));

				list.add(c);

			}

			return list;

		} catch (SQLException e) {
			
			e.printStackTrace();
			throw new RuntimeException("获取连接失败", e);
			
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException("关闭连接失败", e);
			}
		}

	}

}
